package edu.cug.water.crawler.job.task.committee;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import edu.cug.water.crawler.common.annotation.BeanField;
import edu.cug.water.crawler.common.constant.Constant;
import edu.cug.water.crawler.common.constant.EsConstants;
import edu.cug.water.crawler.common.exception.RRException;
import edu.cug.water.crawler.common.utils.DateUtils;
import edu.cug.water.crawler.common.utils.EsUtils;
import edu.cug.water.crawler.job.entity.committee.TaiHuWater;
import edu.cug.water.crawler.job.request.RequestUtil;
import edu.cug.water.crawler.job.task.ITask;
import edu.cug.water.crawler.job.utils.AbstractCrawlerTask;
import edu.cug.water.crawler.job.utils.DataConvertUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Component("job:TaiHuWater")
public class TaiHuWaterTask extends AbstractCrawlerTask<TaiHuWater> implements ITask {

    @Autowired
    private EsUtils esUtils;

    @Autowired
    private RequestUtil requestUtil;

    @Override
    public int run(String params) throws IOException {
        init();

        ResponseEntity<String> response = getRequestBody();

        List<TaiHuWater> results = getDataFromStr(response.getBody());
        log.info("{} converts results：{}", getClass().getName(), results.size());

        Boolean aBoolean = esUtils.statusJudge(esUtils.addDocuments(EsConstants.TypeConstant.TAI_HU_WATER.getValue(), results));
        if (!aBoolean) {
            throw new RRException(getClass().getName() + Constant.LogConstants.THE_PROCESS_OF_ES_STORE_FAILED.getValue());
        }
        return results.size();
    }

    @Override
    protected void init() {
        super.init();
        url = "https://www.tba.gov.cn/TrueCMS/gatewayController/gatewayExempts.do";
        headers.set("Host", "www.tba.gov.cn");
        headers.set("Connection", "keep-alive");
        headers.set("Accept", "application/json, text/javascript, */*; q=0.01");
        headers.set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        headers.set("X-Requested-With", "XMLHttpRequest");
        headers.set("Origin", "https://www.tba.gov.cn");
        headers.set("Referer", "https://www.tba.gov.cn/");
        headers.set("Accept-Encoding", "gzip, deflate, br");
        headers.set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
        headers.set("Cookie", "JSESSIONID=034CF94A0D730EBE87DDCCB984A26FD7; csrftoken=sToken114394; leech_n=txr-NuLzXjM3nzYpaWqVyMUce2DLKjpWnWNLjaziegKt3aJ5R-VIyMUUy6BTchJZrd2ieUflSMjFFMugU3ISWQ%%");


        multiValueMap.add("LY", "Get_Water");
        multiValueMap.add("TM", DateUtils.formatDate(new Date()));
    }

    @Override
    public ResponseEntity<String> getRequestBody() {
        return requestUtil.post(url, headers, multiValueMap);
    }

    @Override
    public List<TaiHuWater> getDataFromStr(String body) {
        if (StringUtils.isEmpty(body)) {
            throw new RRException(getClass().getName() + Constant.LogConstants.RESPONSE_IS_NULL.getValue());
        }
        List<TaiHuWater> results = new ArrayList<>();

        JSONObject parse = (JSONObject) JSONObject.parse(body);
        JSONArray jsonArray = parse.getJSONArray("succes");

        for (Object datum : jsonArray) {
            JSONObject temp = (JSONObject) datum;
            if (temp.get("choice") != null) {
                continue;
            }
            TaiHuWater entity = new TaiHuWater();
            Field[] fields = entity.getClass().getDeclaredFields();

            for (Field field : fields) {
                if (field.getAnnotation(BeanField.class) == null) {
                    continue;
                }
                field.setAccessible(true);
                try {
                    if ("stationCode".equals(field.getName())) {
                        field.set(entity, DataConvertUtil.stationCodeConvert((temp.get(field.getAnnotation(BeanField.class).property()) + "").trim()));
                    } else {
                        field.set(entity, (temp.get(field.getAnnotation(BeanField.class).property()) + "").trim());
                    }
                } catch (IllegalAccessException e) {
                    throw new RRException(getClass().getName() + Constant.LogConstants.FIELD_ASSIGNMENT_ILLEGAL_ACCESS.getValue());
                }
            }
            entity.setCreateTime(DateUtils.formatDateTime(new Date()));
            results.add(entity);
        }
        return results;
    }

}